package org.zero.concurrency.demo.example.count;

import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.NotThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @program: concurrency-demo
 * @description: 模拟并发执行
 * @author: 01
 * @create: 2018-10-14 00:01
 **/
@Slf4j
@NotThreadSafe
public class CountExample4 {
    /**
     * 请求总数
     */
    public static int clientTotal = 5000;

    /**
     * 同时并发执行的线程数量
     */
    public static int threadTotal = 200;

    /**
     * 计数
     */
    private static volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    // 从信号量获取执行许可，若并发达到设定的数量，那么就不会获取到许可，将会阻塞当前线程，直到能够获取到执行许可为止
                    semaphore.acquire();
                    CountExample4.add();
                    // 释放当前线程
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("count: {}", count);
    }

    /**
     * 这个方法是线程不安全的，会有多个线程同时操作count变量
     * 因为volatile只能保证以下三步执行的顺序不会被重排序
     * 但是不保证这三步能够原子执行，即volatile是不具备原子性的
     * 也就是说还是有可能会有两个线程交叉执行这三步，导致执行结果不能确定
     */
    private static void add() {
        // volatile关键字修饰的count变量在自增时主要做了以下三步：
        // 1.取当前内存中的count值
        // 2.count值加1
        // 3.重新写回主内存
        count++;
    }
}
